<template>
    <view>这只是一个数据抓取页面</view>
</template>

<script>
import {virtualCourse} from 'storage.js';
import {COURSE_API} from 'API.js';
export function setCourseToStorage() {
    // 虚拟数据
    var courses = virtualCourse;
    var token = getApp().globalData.user.token;
    // 将课程数据存入缓冲区
    return new Promise((resolve, reject) => {
        uni.request({
            url: COURSE_API.timeTable.url,
            method: COURSE_API.timeTable.method,
            header: {'http-token': token},
            data: {
                'start_at': '2020-01-01',
                'end_at': '2025-12-31'
            },
            success: (res) => {
                if(res.statusCode === 200)
                {
                    courses = courses.concat(res.data);
                }

                // 数据处理:只包含数据及章节列表
                var courseChapter = [];
                for(var e of courses)
                {
                    let hasThisCourse = courseChapter.find(function(x) {
                        return x.course.id === e.course_id;
                    });
                    if(hasThisCourse == undefined)
                    {
                        courseChapter.push({
                            'course': {'id': e.course_id, 'name': e.title},
                            'chapters': [e],
                        });
                    }
                    else
                    {
                        hasThisCourse.chapters.push(e);
                    }
                }

                // 将数据加入缓冲区
                uni.setStorageSync('FullCourses', courses);
                uni.setStorageSync('CourseWithChapter', courseChapter);
                /*
                 * console.log('courses save complete!!!');
                 * console.log("courseChapters is:"+JSON.stringify(courseChapter));
                 */
                resolve('suc');
            },
            fail: ()  => {
                //console.log('heres the fail ');
                reject('err');
            },
            complete: () => {
                //console.log('complete request Course:' + res.statusCode);
            }
        });
    });
}

export default{

};

</script>

<style>
</style>
